<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ResetPwdController extends Controller
{

    public function showResetForm(Request $request)
    {
        if (!!$request->user()->pwd_reset) {
            return redirect()->route('admin');
        }

        return view('auth.passwords.pwd');
    }

    public function reset(Request $request)
    {
        $user = $request->user();

        $data = $this->validate($request, [
            'password' => ['required', 'string', 'between:8,16', 'letters', 'case_diff', 'numbers', 'symbols', 'confirmed',
                function ($attribute, $password, $fail) use ($user) {
                    if ($user->email == $password) {
                        $fail(trans('validation.pwd_email_diff'));
                    }
                }
            ],
        ]);

        // 更新 remember_token
        $user->setRememberToken(Str::random(60));
        // 修改密码
        $user->password = Hash::make($data['password']);
        // 标记重置
        $user->pwd_reset = 1;
        // 保存密码
        $user->save();

        // 重新登录
        Auth::guard('web')->login($user);

        return redirect()->route('admin');
    }
}
